package com.yi.wood.web.service.impl;

import com.yi.wood.entity.Classification;
import com.yi.wood.service.impl.AbstractClassificationServiceImpl;
import com.yi.wood.web.ctrl.dto.ClassificationDto;
import com.yi.wood.web.service.ClassificationProService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author MoYi
 * create date 2019/4/5 20:02
 */
@Service("classificationProService")
public class ClassificationProServiceImpl extends AbstractClassificationServiceImpl implements ClassificationProService {


    @Override
    public Map<Long, ClassificationDto> list(Long parentId, String name, Integer level, Integer type) {
        List<Classification> list1 = queryClassByLevel(1, type);
        List<Classification> list2 = queryClassByLevel(2, type);

        Map<Long, ClassificationDto> dtoMap = new HashMap<>(list1.size());
        // 第一次循环是获取第一层分类列表
        list1.forEach(classification -> {
            ClassificationDto dto = new ClassificationDto();
            dto.setChildren(new ArrayList<>());
            BeanUtils.copyProperties(classification, dto);
            dtoMap.put(dto.getId(),dto);
        });

        // 第二次循环封装第二层分类列表
        list2.forEach(classification -> {
            ClassificationDto dto = new ClassificationDto();
            BeanUtils.copyProperties(classification, dto);
            ClassificationDto hasChildren = dtoMap.get(classification.getParentId());
            if (!Objects.isNull(hasChildren)){
                if (Objects.isNull(hasChildren.getChildren())){
                    hasChildren.setChildren(new ArrayList<>());
                }
                hasChildren.getChildren().add(dto);
            }
        });

        return dtoMap;
    }
}
